<?php

namespace app\xcxapi\service;

use app\common\service\BaseService;
use app\lib\exception\BaseException;
use app\models\CampusModel;
use app\models\ConsultorModel;
use app\models\CourseLogModel;
use app\models\CourseModel;
use app\models\CourseContractModel;
use app\models\GoodsContractModel;
use app\models\GradesContractModel;
use app\models\ContractModel;
use app\models\DictionaryModel;
use app\models\FollowUpLogModel;
use app\models\GradesDetailsListsModel;
use app\models\GradesDetailsModel;
use app\models\MarkingModel;
use app\models\MenuModel;
use app\models\ParentInformationModel;
use app\models\PayFlowModel;
use app\models\PushMessageModel;
use app\models\StudentModel;
use app\models\StudentSubjectClassModel;
use app\models\StudentSubjectInfosClassModel;
use app\models\UserModel;
use think\Db;

/**
 * Class CommonService.
 */
class CommonService extends BaseService
{
    public static function mergeCate($arr, $pidName, $parent_id = 0, $level = 0)
    {
        $res = [];
        foreach ($arr as $v) {
            if ($v[$pidName] == $parent_id) {
                $v['disabled'] = false;
                foreach ($arr as $v1) {
                    if ($v1[$pidName] == $v['id']) {
                        $v['disabled'] = true;

                        break;
                    }
                }

                $v['level'] = $level;
                $res[] = $v;
                $res = array_merge($res, self::mergeCate($arr, $pidName, $v['id'], $level + 1));
            }
        }

        return $res;
    }

    /**
     * @param $ad_p_name
     *
     * @return mixed
     */
    public static function getContentType($ad_p_name)
    {
        $where = [
            'ad_name' => $ad_p_name,
        ];

        return PositionModel::where($where)->value('ad_type');
    }

    /**
     * 获取广告类型.
     *
     * @param $ad_s_id
     *
     * @return mixed
     */
    public static function getSubjectName($ad_s_id)
    {
        $where = [
            'id' => $ad_s_id,
        ];

        return SubjectModel::where($where)->value('ad_m');
    }

    /**
     * 获取当前的pid.
     *
     * @param $title
     * @param $controller
     * @param $action
     *
     * @return mixed
     */
    public static function getCurrentPid($title, $controller, $action)
    {
        $code = $controller.'/'.$action;
        $memuModel = new MenuModel();
        $condition = [
            'title' => $title,
            'menu_name' => $code,
        ];

        return $memuModel->where($condition)->value('pid');
    }

    /**
     * 获取pid.
     *
     * @param $title
     * @param $menu_name
     *
     * @return mixed
     */
    public static function getTwoPid($title, $menu_name)
    {
        $memuModel = new MenuModel();
        $condition = [
            'title' => $title,
            'menu_name' => $menu_name,
        ];

        return $memuModel->where($condition)->value('pid');
    }

    /**
     * 获取上级标题名称.
     *
     * @param $pid
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     *
     * @return array|false|\PDOStatement|string|\think\Model
     */
    public static function getSuperiorTitle($pid)
    {
        $memuModel = new MenuModel();

        return $memuModel->where('id', $pid)->find();
    }

    /**
     * 获取当前标题名称.
     *
     * @param $controller
     * @param $action
     *
     * @return mixed
     */
    public static function getCurrentTitle($controller, $action)
    {
        $code = $controller.'/'.$action;
        $memuModel = new MenuModel();

        return $memuModel->where('menu_name', $code)->value('title');
    }

    /**
     * 获取广告类型.
     *
     * @param mixed $type
     */
    public static function getAdType($type)
    {
        $value = '';
        switch ($type) {
            case 1:
                $value = '图片';

                break;
            case 2:
                $value = '文字';

                break;
            case 3:
                $value = '图文';

                break;
            case 4:
                $value = '动画';

                break;
            case 5:
                $value = '视频';

                break;
            case 6:
                $value = '短信';

                break;
            case 7:
                $value = '链接';

                break;
            case 8:
                $value = '二维码';

                break;
        }

        return $value;
    }

    /**
     * 写入订单操作人记录.
     *
     * @param $uid
     * @param $name
     * @param $ordernumber 订单号
     * @param $ctype 操作类型
     * @param $wtype 工作类型
     * @param $content 操作描述
     */
    public static function writeOrderOperatorRecord($uid, $name, $ordernumber, $ctype, $wtype, $content)
    {
        $data = [
            'order_number' => $ordernumber,
            'user_id' => $uid,
            'user_name' => $name,
            'ctype' => $ctype,
            'wtype' => $wtype,
            'content' => $content,
            'operation_time' => date('Y-m-d H:i:s', time()),
        ];
        OrderLogModel::create($data);
    }

    /**
     * 写入退货、退单记录.
     *
     * @param $code 支付单号
     * @param $ordernumber 订单号
     * @param $order_list_id 订单商品列表ID
     * @param $proid 商品id
     * @param $num 商品数量
     * @param $price 金额
     * @param $type 订单操作类型 0-取消 1-异常
     */
    public static function writeFlagRecord($code, $ordernumber, $order_list_id, $proid, $num, $price, $type)
    {
        $refund_number = 'TK'.time();
        $data = [
            'code' => $code, //支付单号
            'order_number' => $ordernumber, //订单号
            'refund_number' => $refund_number, //退款单号
            'order_list_id' => $order_list_id, //订单商品列表ID
            'pro_id' => $proid, //商品ID
            'num' => $num, //商品数量
            'price' => $price, //金额
            'type' => $type, //订单操作类型 0-取消 1-异常
            'status' => 0, //1：已退款，0：未退款 默认0
        ];
        OrderFlagModel::create($data);
    }

    /**
     * 写入车厢退款金额记录.
     *
     * @param $order_code
     * @param $paytime
     * @param $paydate
     * @param $amount
     * @param $protype
     * @param $mch_id
     * @param $mch_name
     * @param $base_id
     * @param $base_name
     * @param $remark
     * @param $trxid
     */
    public static function writeInRefundFeeRecord($order_code, $paytime, $paydate, $amount, $protype, $mch_id, $mch_name, $base_id, $base_name, $remark, $trxid)
    {
        $data = [
            'order_code' => $order_code, //支付单号
            'paytime' => $paytime, //时间戳
            'paydate' => $paydate, //时间
            'amount' => -$amount, //金额
            'type' => 2, //流水类型：1收入，2退款
            'protype' => $protype, //0：外卖，1：车厢，-1：长尾（优选）
            'mch_id' => $mch_id, //商户号
            'mch_name' => $mch_name, //商户名称
            'base_id' => $base_id, //基地ID
            'base_name' => $base_name, //基地名称
            'trxid' => $trxid, //平台支付单号
            'remark' => $remark,
        ];
        PayFlowAModel::create($data);
    }

    /**
     * 写入外卖、长尾、优选退款金额记录.
     *
     * @param $order_code
     * @param $paytime
     * @param $paydate
     * @param $amount
     * @param $protype
     * @param $mch_id
     * @param $mch_name
     * @param $com_id
     * @param $com_name
     * @param $remark
     * @param $trxid
     */
    public static function writeOutRefundFeeRecord($order_code, $paytime, $paydate, $amount, $protype, $mch_id, $mch_name, $com_id, $com_name, $remark, $trxid)
    {
        $data = [
            'order_code' => $order_code, //支付单号
            'paytime' => $paytime, //时间戳
            'paydate' => $paydate, //时间
            'amount' => -$amount, //金额
            'type' => 2, //流水类型：1收入，2退款
            'protype' => $protype, //0：外卖，1：车厢，-1：长尾（优选）
            'mch_id' => $mch_id, //商户号
            'mch_name' => $mch_name, //商户名称
            'com_id' => $com_id, //公司ID
            'com_name' => $com_name, //公司名称
            'trxid' => $trxid, //平台支付单号
            'remark' => $remark,
        ];
        PayFlowBModel::create($data);
    }

    /**
     * @param $ds_com
     *
     * @return string
     */
    public static function getCompanyText($ds_com)
    {
        $value = '';
        switch ($ds_com) {
            case 'shentong':
                $value = '申通快递';

                break;
            case 'yuantong':
                $value = '圆通速递';

                break;
            case 'zhongtong':
                $value = '中通快递';

                break;
            case 'huitongkuaidi':
                $value = '百世汇通';

                break;
            case 'yunda':
                $value = '韵达快递';

                break;
            case 'shunfeng':
                $value = '顺丰快递';

                break;
            case 'youzhengguonei':
                $value = '邮政快递';

                break;
        }

        return $value;
    }

    /**
     * 订单类型.
     *
     * @param $protype
     *
     * @return string
     */
    public static function getProtypeText($protype)
    {
        $value = '';
        switch ($protype) {
            case -1:
                $value = '长尾订单';

                break;
            case 0:
                $value = '外卖订单';

                break;
            case 1:
                $value = '车厢订单';

                break;
        }

        return $value;
    }

    /**
     * 支付状态
     *
     * @param $pay_status
     *
     * @return string
     *                支付状态 0:未支付;1:已支付;2:部分退款;3:已退款;
     */
    public static function getPayStatusText($pay_status)
    {
        $value = '';
        switch ($pay_status) {
            case 0:
                $value = '未支付';

                break;
            case 1:
                $value = '已支付';

                break;
            case 2:
                $value = '部分退款';

                break;
            case 3:
                $value = '已退款';

                break;
        }

        return $value;
    }

    /**
     * 订单状态
     *
     * @param $status
     *
     * @return string
     *                订单状态 0:已下单;1:已支付;2:已接单;3:已完成;4:已取消;5:已关闭;-1:已作废;
     */
    public static function getStatusText($status)
    {
        $value = '';
        switch ($status) {
            case -1:
                $value = '已作废';

                break;
            case 0:
                $value = '已下单';

                break;
            case 1:
                $value = '已支付';

                break;
            case 2:
                $value = '已接单';

                break;
            case 3:
                $value = '已完成';

                break;
            case 4:
                $value = '已取消';

                break;
            case 5:
                $value = '已关闭';

                break;
        }

        return $value;
    }

    /**
     * 支付方式.
     *
     * @param $paytype
     *
     * @return string
     *                支付方式:0未知,1微信支付,2支付宝,3通联支付,4京东支付,5建行支付,6现金支付
     */
    public static function getPaytypeText($paytype)
    {
        $value = '';
        switch ($paytype) {
            case 0:
                $value = '未知';

                break;
            case 1:
                $value = '微信支付';

                break;
            case 2:
                $value = '支付宝';

                break;
            case 3:
                $value = '通联支付';

                break;
            case 4:
                $value = '京东支付';

                break;
            case 5:
                $value = '建行支付';

                break;
            case 6:
                $value = '现金支付';

                break;
        }

        return $value;
    }

    /**
     * 订单来源.
     *
     * @param $ordertype
     *
     * @return string
     *                订单来源  0:商城订单1:手机当面付2:手工下单3:扫码下单4:金额下单5:OTA订单6:12306下单
     */
    public static function getOrdertypeText($ordertype)
    {
        $value = '';
        switch ($ordertype) {
            case 0:
                $value = '商城订单1';

                break;
            case 1:
                $value = '手机当面付';

                break;
            case 2:
                $value = '手工下单';

                break;
            case 3:
                $value = '扫码下单';

                break;
            case 4:
                $value = '金额下单';

                break;
            case 5:
                $value = 'OTA订单';

                break;
            case 6:
                $value = '12306下单';

                break;
        }

        return $value;
    }

    /**
     *  获取字典名称.
     *
     * @param $id
     *
     * @throws \think\exception\DbException
     *
     * @return array
     */
    public static function getDictionaryName($id)
    {
        if (!is_numeric($id)) {
            return [];
        }

        return DictionaryModel::get($id)['name'];
    }

    /**
     * 生成单号.
     *
     * @return string
     */
    public static function generateNumber()
    {
        $number = '';
        $year = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
        $number .= $year[(int) (date('Y')) - 2019].date('mdHis').substr(microtime(), 2, 3).sprintf('%02d', rand(0, 99));

        return $number;
    }

    /**
     * 生成学号.
     *
     * @return string
     */
    public static function generateStudentNumber()
    {
        $number = '';
        $year = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
        $number .= 'X'.$year[(int) (date('Y')) - 2019].date('mdHis').substr(microtime(), 2, 3).sprintf('%02d', rand(0, 99));

        return $number;
    }

    /**
     * User: wufeng
     * Date: 2019/4/16.
     *
     * @param $contract_number
     * @param $type
     * @param $amount
     * @param $remark
     * @param $campus_id
     * @param $receipt_number
	 * @param $pay_channel
     */
    public static function writeFlowRecord($contract_number, $type, $amount, $remark, $campus_id, $receipt_number, $pay_channel)
    {
        $data = [
            'contract_number' => $contract_number, //订单编号
            'operator' => xcxapi_get_current_name(),
            'paytime' => time(), //时间戳
            'paydate' => date('Y-m-d H:i:s', time()), //时间
            'type' => $type, //流水类型：1收入，2退款
            'remark' => $remark,
            'receipt_number' => $receipt_number,
            'campus_id' => $campus_id,
			'pay_channel' => $pay_channel //付款通道
        ];
        if (1 === (int) $type) {
            $data['amount'] = $amount; //金额
        } elseif (2 === (int) $type) {
            $data['amount'] = -$amount; //金额
        }

        PayFlowModel::create($data);
    }

    /**
     * @param $contract_number
     * @param $course
     * @param $campus
     */
    public static function writeCourseRecord($contract_number, $course, $campus, $record_status)
    {
        $data = [
            'contract_number' => $contract_number, //订单编号
            'course' => $course, //课程
            'campus' => $campus, //校区
			'record_status' => $record_status, //记录来源
        ];
        CourseLogModel::create($data);
    }
	

    /**
     * @param $student_id
     * @param $contract_number
     * @param $contract_type
     */
    public static function writeSignContract($student_id, $contract_number, $contract_type)
    {
        $data = [
            'student_id' => $student_id, //学员ID
            'contract_number' => $contract_number, //签约订单编号
            'contract_type' => $contract_type, //类型
        ];
        ConsultorModel::create($data);
    }

    /**
     * @param $status
     *
     * @return string
     */
    public static function getContractText($status)
    {
        $value = '';
        switch ($status) {
            case '1':
                $value = '已付款';

                break;
            case '2':
                $value = '未付款';

                break;
        }

        return $value;
    }

    /**
     * 学员客户跟进沟通记录写入
     * modify by Small Y.
     *
     * @param $sid
     * @param $user_id
     * @param $campus_id
     * @param $type
     * @param $content
     * @param $mode
     * @param $follow_up
     */
    public static function writeFollowUpLog($sid, $user_id, $campus_id, $type, $content, $mode, $follow_up)
    {
        $data = [
            'student_id' => $sid, //学员客户ID
            'campus_id' => $campus_id, //校区id
            'user_id' => $user_id,
            'timestamp' => time(), //时间戳
            'date' => date('Y-m-d', time()), //日期
            'time' => date('Y-m-d H:i:s', time()), //时间
            'type' => $type, //类型：1系统跟进，2沟通
            'content' => $content,
            'mode' => $mode,
            'follow_up' => $follow_up, //跟进状态：33未分配 34未处理 35已跟进 36已预约 103已上门 104已交定金 105已丢单
        ];
        FollowUpLogModel::create($data);
    }

	/**
	 * User: wufeng
	 * Date: 2020/03/14
	 *
	 * @param $notice_object
	 * @param $notice_name
	 * @param $notice_content
	 * @param $flag  1:家长端  2:机构端
	 * @param $notice_type  1:普通通知  2:系统通知
	 */
    public static function writeNotice($notice_object,$notice_name,$notice_content,$flag,$notice_type)
    {
		//审批通知
		$notice = [];
		$notice['notice_time'] = date('Y-m-d H:i:s'); //通知时间
		$notice['user_id'] = xcxapi_get_current_user_id(); //操作审批人的id
		$notice['notice_object'] = $notice_object; //通知对象
		$notice['notice_name'] = $notice_name; //通知名称
		$notice['content'] = $notice_content; //具体内容
		$notice['notice_type'] = 1; //通知方向：1机构端、家长端；2机构端；3家长端
		$notice['status'] = 1; //存稿还是发布：1发布 2存稿

		Db::name('edu_my_notice')->insert($notice);  //插入通知表
		$notice_id = Db::name('edu_my_notice')->getLastInsID();
		$_data = [];
		$notices = explode(',', $notice['notice_object']);
		foreach ($notices as &$notice) {
			$arr = [];
			$arr['notice_id'] = $notice_id;
			$arr['notice_object_id'] = $notice;
			$arr['n_type'] = $flag;
			$arr['notice_type'] = $notice_type;
			$_data[] = $arr;
		}
		Db::name('edu_my_notice_object')->insertAll($_data);
    }

    /**
     * 选择客户
     * User: wufeng
     * Date: 2020/01/06.
     *
     * @param $params
     *
     * @return array
     */
    public function selectCustomer($params)
    {
        try {
            $where = [];
			//按手机号、姓名搜索
			if (isset($params['word']) && '' !== $params['word']) {
				$where['phone|student_name|name'] = ['like', '%'.$params['word'].'%'];
			}
			if(5 === (int) xcxapi_get_current_wtype()){
				$where['user_id'] = xcxapi_get_current_user_id();
			}else{
				$where['campus_id'] = ['in',xcxapi_get_current_campus_id()];
			}
            $this->data = (new StudentModel())
                ->where($where)
				->order('id desc')
                ->select()
                ->toArray();
				foreach ($this->data as &$item) {
					 /*录入类型，如果存在该生合同则为老生，否则为新生*/
					$res = (new ContractModel())->get(['student_id' => $item['id']]);
					if(!$res){
						$item['input_type'] = 0;  //新生
					}else{
						$item['input_type'] = 1;  //老生
					}
					
				}
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

    /**
     * 批阅
     * User: wufeng
     * Date: 2020/02/20.
     *
     * @param $params
     *
     * @return mixed
     */
    public function marking($params)
    {
        try {
            $data['lid'] = $params['lid']; // 跟进记录id
            $data['marking'] = $params['marking']; // 批阅内容
            $data['time'] = date('Y-m-d H:i:s'); // 批阅时间
            $data['name'] = xcxapi_get_current_name(); // 操作人
            $data['img'] = xcxapi_get_current_img(); // 操作人头像
            (new MarkingModel())->save($data);
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

    /**
     * 发起协同
     * User: wufeng
     * Date: 2020/02/20.
     *
     * @param $params
     *
     * @return mixed
     */
    public function pushMessage($params)
    {
		try {
			$data = [];
			$data['approval_time'] = date('Y-m-d H:i:s'); //审批时间
			$data['user_id'] = xcxapi_get_current_user_id(); //发布人id
			$data['content'] = $params['content']; //具体内容
			$data['picture'] = $params['picture'];
			$data['audio'] = $params['audio'];
			$data['audio_duration'] = $params['audio_duration'];
			$data['video'] = $params['video'];
			$data['operation_type'] = 2;
			$data['approver'] = $params['approver'];
			$data['approval_name'] = '协同申请';
			$data['type'] = 1;
			$data['coordination_time'] = $params['coordination_time'];  //协同时间
			$data['reminder_time'] = $params['reminder_time']; //提醒时间间隔
			$data['students'] = $params['students'];
			$data['status'] = 1;
			Db::name('edu_my_approval')->insert($data);
			$id = Db::name('edu_my_approval')->getLastInsID();
			$_data = [];
			$approver_ids = explode(',', $params['approver']);
			foreach ($approver_ids as &$approver_id) {
				$approver = [];
				$approver['approval_id'] = $id;
				$approver['approver_id'] = $approver_id;
				$approver['status'] = 1;
				$_data[] = $approver;
			}
			Db::name('edu_my_approval_relation')->insertAll($_data);
			//写入通知记录
			CommonService::writeNotice($params['approver'],'协同申请','收到了'.xcxapi_get_current_name().'协同申请',2, 1);
		} catch (\Exception $e) {
			$this->errorMessage($e, $params);
		}

		return $this->return;
    }

    /**
     * 年级、来源、课程顾问
     * User: wufeng
     * Date: 2020/02/20.
     *
     * @return mixed
     */
    public function dataList()
    {
        try {
            $where = [];
            $where['campus_id'] = ['in', xcxapi_get_current_campus_id()];
            $where['status'] = 1;
            $this->data['student'] = (new UserModel())
                ->where($where)
				->order('id desc')
                ->field('id,name')
                ->select()
                ->toArray()
            ;
            $arr[] = [
                'id' => 0,
                'name' => '公海',
            ];
            $this->data['student'] = array_merge($this->data['student'], $arr);
            $this->data['class'] = (new DictionaryModel())
                ->where('type', 1)
                ->field('id,name')
                ->select()
                ->toArray()
            ;
            $this->data['channel'] = (new DictionaryModel())
                ->where('type', 2)
                ->field('id,name')
                ->select()
                ->toArray()
            ;
			   
			$this->data['guardian'] = (new DictionaryModel())
                ->where('type', 30)
                ->field('id,name')
                ->select()
                ->toArray()
			;

        } catch (\Exception $e) {
            $this->errorMessage($e, '');
        }

        return $this->return;
    }

    /**
     * 跟进状态/沟通方式
     * User: wufeng
     * Date: 2020/02/20.
     *
     * @return mixed
     */
    public function followUpLinkUp()
    {
        try {
            $this->data['follow_up'] = (new DictionaryModel())
                ->where('type', 6)
                ->field('id,name')
                ->select()
                ->toArray()
            ;
            $this->data['link_up'] = (new DictionaryModel())
                ->where('type', 29)
                ->field('id,name')
                ->select()
                ->toArray()
            ;
        } catch (\Exception $e) {
            $this->errorMessage($e, '');
        }

        return $this->return;
    }

    /**
     * 选择同事
     * User: wufeng
     * Date: 2020/02/20.
     *
     * @param $params
     *
     * @return mixed
     */
    public function selectColleague($params)
    {
        try {
            $where = [];
            $where['campus_id'] = ['in', xcxapi_get_current_campus_id()];
            $this->data = (new UserModel())
                ->where($where)
				->order('id desc')
                ->field('id,name,mobile,campus_id')
                ->select()
                ->toArray()
            ;
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

    /**
     * 转给同事
     * User: wufeng
     * Date: 2020/02/20.
     *
     * @param $params
     *
     * @return mixed
     */
    public function revolveColleague($params)
    {
        try {
            $name = (new UserModel())->get(['id' => $params['user_id']])['name'];
            (new StudentModel())->save(['course_consultant_type' => 1, 'campus_id' => xcxapi_get_current_campus_id(),  'user_id' => $params['user_id'], 'course_consultant' => $name], ['id' => $params['id']]);
            // 学员学员跟进沟通记录写入
            $student = (new StudentModel())->get($params['id']);
            self::writeFollowUpLog($params['id'], xcxapi_get_current_user_id(), xcxapi_get_current_campus_id(), 1, xcxapi_get_current_name().' '.'将学员'.' '.$student['student_name'].' '.'转给了同事'.' '.$name, 1, $student['follow_up']);
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

    /**
     * 参与人/提醒时间
     * User: wufeng
     * Date: 2020/02/20.
     *
     * @param $params
     *
     * @return mixed
     */
    public function participantReminderTime($params)
    {
        try {
            $where = [];
            $where['campus_id'] = ['in', xcxapi_get_current_campus_id()];
            $this->data['user'] = (new UserModel())
                ->where($where)
				->order('id desc')
                ->field('id,name,campus_id')
                ->select()
                ->toArray()
            ;
            $this->data['time'] = (new DictionaryModel())
                ->where('type', 31)
                ->field('id,name')
                ->select()
                ->toArray()
            ;
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

    /**
     * 写入跟进
     * User: wufeng
     * Date: 2020/01/09.
     *
     * @param $params
     *
     * @return array
     */
    public function writeFollowUpRecord($params)
    {
        try {
            $data = [];
            $data['timestamp'] = time(); // 跟进记录时间戳
            $data['time'] = date('Y-m-d H:i:s'); // 跟进记录时间
            $data['date'] = date('Y-m-d'); // 跟进记录日期
            $data['student_id'] = $params['id']; // 学员ID
            $data['user_id'] = xcxapi_get_current_user_id(); // 操作人ID
            $data['img'] = xcxapi_get_current_img(); // 操作人头像
            $data['campus_id'] = ['in', xcxapi_get_current_campus_id()]; // 当前校区
            $data['type'] = 2; // 沟通记录
            $data['next_follow_up_date'] = $params['next_follow_up_date']; //下次跟进日期
            $data['intentional_course'] = $params['intentional_course']; //意向课程
            $data['intentional_grade'] = $params['intentional_grade']; //意向级别
            $data['content'] = $params['content']; //跟进内容
            $data['follow_up'] = $params['follow_up']; //跟进状态
            if (36 === (int) $data['follow_up']) {
                $data['drop_in_date'] = $params['visiting_date']; //上门时间
            }
            $data['mode'] = $params['mode']; //沟通方式
            $data['growth_record'] = $params['growth_record']; //是否标为成长记录：1是 0否
            Db::name('edu_follow_up_log')->insert($data);
            $_data = [
                'intentional_course' => $data['intentional_course'], //意向课程
                'intentional_grade' => $data['intentional_grade'], //意向级别
                'follow_up' => $data['follow_up'], //跟进状态
                'next_follow_up_record' => $data['next_follow_up_date'], //跟进日期
				'next_follow_up_timestamp'=>strtotime($data['next_follow_up_date']),//跟进时间戳
            ];
			if (36 === (int) $data['follow_up']) {
				$_data['visiting_date'] = $params['visiting_date']; //上门时间
				$_data['visiting_timestamp'] = strtotime($params['visiting_date']); //上门时间
			}
            (new StudentModel())->save($_data, ['id' => $data['student_id']]);
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

    /**
     * User: wufeng
     * Date: 2020/02/27.
     *
     * @param $params
     *
     * @return mixed
     */
    public function signInIndex($params)
    {
        try {
            $where = [];
            $where['campus_id'] = ['in', xcxapi_get_current_campus_id()];
            $where['graduation_status'] = 0;//0表示未结业，1表示已经结业
            $this->data = (new GradesDetailsListsModel())
                ->where($where)
				->order('id desc')
                ->select()
                ->toArray();
            foreach ($this->data as &$index) {
                $index['actual_number'] = (new StudentSubjectInfosClassModel())->where(['class_manage_details_id' => $index['id'], 'attendance' => 1])->count();
                $index['should_number'] = (new StudentSubjectInfosClassModel())->where(['class_manage_details_id' => $index['id']])->count();
				$index['course_type'] = CourseModel::get(['id' => $index['course_id']])['course_type'];
				$index['course_type_text'] = DictionaryModel::get(['id' => $index['course_type']])['name'];
            }
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

	/**
	 * User: wufeng
	 * Date: 2020/03/21
	 *
	 * @param $params
	 * @return array
	 */
    public function signInDetailLists($params)
    {
        try {
            $where = [];
            $where['class_manage_details_id'] = $params['id'];
			$this->data= (new StudentSubjectInfosClassModel())
                ->where($where)
				->order('id desc')
                ->select()
                ->toArray();
			foreach ($this->data as &$index) {	
				$index['student_type'] = (new StudentSubjectClassModel())->get(['class_subject_id' => $index['class_subject_id'], 'student_id' => $index['student_id'], 'contract_number' => $index['contract_number']])['student_type'];	
			}
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

	/**
	 * User: wufeng
	 * Date: 2020/03/21
	 *
	 * @param $params
	 * @return array
	 */
    public function signInDel($params)
    {
        try {
			$id = $params['id'];
			$api_type = $params['api_type'];
			if($api_type == 4){ //删除所有 已上课
				if(!(new StudentSubjectInfosClassModel())->where(['class_manage_details_id' => $id])->delete()){
                    $this->error('删除学生课节失败', null, -1, 1);
                }
			}else if($api_type == 3){  //删除所有 未上课
            $result = (new GradesDetailsListsModel())->get(['id' => $id]);
            $result_grade_status = (new GradesDetailsModel())->get(['id' => $result['class_manage_id']])['class_status'];
            if($result_grade_status == 0){
                $result_info_result = (new StudentSubjectInfosClassModel())->where(['class_manage_details_id'=> $id])->select(); //获取当前所有该节课学生课时
                foreach ($result_info_result as $key => $value){
                    if($value['follow_status'] == 2){   //跟班学员

                        $id_ = $value['lessons_id'];
                        if(!(new StudentSubjectInfosClassModel())->save(['lessons_status' => 0],['id' => $id_])){
                            $this->error('更新该学生状态失败', null, -1, 1);
                        }

                        if(!(new StudentSubjectInfosClassModel())->where(['id' => $value['id']])->delete()){
                            $this->error('删除该学生课节失败', null, -1, 1);
                        }


                        if(!(new StudentSubjectInfosClassModel())->where(['class_subject_id' => $value['class_subject_id'], 'student_type' => 3, 'student_id' => $value['student_id']])->delete()){
                            $this->error('删除分班补课学生失败', null, -1, 1);
                        }


                    }else{
                        (new StudentSubjectInfosClassModel())->where(['id' => $value['id']])->delete();
                    }
                }

            }else{

                //释放补课学员
                $student_lesson_result =  (new StudentSubjectInfosClassModel())->where(['class_manage_details_id' => $id])->select();


                foreach ($student_lesson_result as $key => $value){
                    $lessons_id = $value['lessons_id']; //所绑课程ID
                    if(!(new StudentSubjectInfosClassModel())->where(['id' => $lessons_id])->update(['lessons_status' => 0])){
                        $this->error('更新该补课学生状态失败', null, -1, 1);
                    }
                }

                if(!(new StudentSubjectClassModel())->where(['class_subject_id' => $result['class_manage_id']])->delete()){
                    $this->error('删除分班补课学生失败', null, -1, 1);
                }

                if(!(new GradesDetailsListsModel())->where(['id' => $id])->delete()){
                    $this->error('删除该补课学生课节失败', null, -1, 1);
                }
                if(!(new GradesDetailsModel())->where(['id' => $result['class_manage_id']])->delete()){
                    $this->error('删除该补课学生班级失败', null, -1, 1);
                }

                if(!(new StudentSubjectInfosClassModel())->where(['class_manage_details_id' => $id])->delete()){

                    $this->error('删除补课所有学生课节失败', null, -1, 1);
                }

            }
			}else if($api_type == 2){  //未上课
			$result = (new StudentSubjectInfosClassModel())->get(['id' => $id]);
            $class_manage_details_id = $result['class_manage_details_id'];
            $class_subject_id = $result['class_subject_id'];
            if($result['lessons_id'] == -1){  //不是补课记录
                if(!(new StudentSubjectInfosClassModel())->where(['id' => $id])->delete()){
                    $this->error('删除该学生课节失败', null, -1, 1);
                }
            }else{

                if($result['follow_status'] == 1) {  //新开班课节

                    $id_ = $result['lessons_id'];
                    if(!(new StudentSubjectInfosClassModel())->save(['lessons_status' => 0],['id' => $id_])){
                        $this->error('更新该学生状态失败', null, -1, 1);
                    }

                    if(!(new StudentSubjectInfosClassModel())->where(['id' => $id])->delete()){
                        $this->error('删除该学生课节失败', null, -1, 1);
                    }

                    if((new StudentSubjectInfosClassModel())->where(['class_subject_id' => $class_subject_id])->count() <= 0){ //是否删完

                        if(!(new StudentSubjectInfosClassModel())->where(['class_subject_id' => $class_subject_id])->delete()){
                            $this->error('删除分班补课学生失败', null, -1, 1);
                        }

                        if((new GradesDetailsListsModel())->where(['id' => $class_manage_details_id])->count() > 0) {
                            if (!(new GradesDetailsListsModel())->where(['id' => $class_manage_details_id])->delete()) {
                                $this->error('删除该补课学生课节失败', null, -1, 1);
                            }
                        }
                        if((new GradesDetailsModel())->where(['id' => $class_subject_id])->count() > 0){
                            if(!(new GradesDetailsModel())->where(['id' => $class_subject_id])->delete()){
                                $this->error('删除该补课学生班级失败', null, -1, 1);
                            }

                        }


                    }
                }else if($result['follow_status'] == 2) {  //新开班课节

                    $id_ = $result['lessons_id'];
                    if(!(new StudentSubjectInfosClassModel())->save(['lessons_status' => 0],['id' => $id_])){
                        $this->error('更新该学生状态失败', null, -1, 1);
                    }

                    if(!(new StudentSubjectInfosClassModel())->where(['id' => $id])->delete()){
                        $this->error('删除该学生课节失败', null, -1, 1);
                    }


                    if(!(new StudentSubjectClassModel())->where(['class_subject_id' => $class_subject_id, 'student_type' => 3, 'student_id' => $result['student_id']])->delete()){
                        $this->error('删除分班补课学生失败', null, -1, 1);
                    }

                }

            }
			}else if($api_type == 1){ //已上课
				if(!(new StudentSubjectInfosClassModel())->where(['id' => $id])->delete()){
					$this->error('删除该学生课节失败', null, -1, 1);
				}
			}
			
			
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }
	
	/**
	 * User: chenben 
	 * Date: 2020/03/24
	 *
	 * @param $params
	 * @return array
	 */
    public function rollCall($params)
    {
        try {
			$data = $params['data'];
			$class_id = $params['id']; //课节ID
			$api_type = $params['api_type']; //类型  
			
			if($api_type == 2){  //未上课	
			$result = (new StudentSubjectInfosClassModel())
				->where(['class_manage_details_id' => $class_id])
				->order('id desc')
				->select();
            $class_subject_id = -1;  //该班级ID
            $infos = [];
            $public_course_id = -1;  //公共课程ID
            foreach ($result as $key => $value){
                        $item = [];
                        $class_subject_id = $value['class_subject_id'];
                        $item['contract_number'] = $value['contract_number'];
                        $item['id'] = $value['id'];
                        $item['course_id'] = $value['course_id'];
                        $item['surplus_class_elimination'] = $value['surplus_class_elimination'];
                        $item['surplus_class_elimination_give'] = $value['surplus_class_elimination_give'];
                        $item['charging'] =  $value['charging'];
                        $item['report_status'] = $value['report_status']; // 来源
                        $public_course_id = $value['course_id'];
                        $postion_key = $item['id'].'';
                        $infos[$postion_key] = $item;
            }


            $update_save_data = [];
            $update_save_contract_data = [];
            $update_arrears_status_student_arr = [];   //欠费状态数组
            $arr_json_lists = $data;
            for ($i = 0; $i < count($arr_json_lists); $i++) {
                $item = $arr_json_lists[$i];
                $cell = [];

                $cell['attendance'] = $item['attendance'];  //出勤
                $cell['charging'] = $item['charging'];  //计费

                $cell['id'] = $item['id'];  //id
                $cell['student_id'] = $item['student_id'];  //student_id
                $cell['attendance_reasons'] = $item['attendance_reasons'];  //缺勤reasons
                $cell['remarks'] = $item['remarks'];  //备注
                $cell['remarks_area'] = $item['remarks_area'];  //课节备注
                $cell['content_area'] = $item['content_area'];  //课节内容

                $contract_number = $infos[$item['id'].'']['contract_number'];  //对应的订单号
                $course_id = $infos[$item['id'].'']['course_id'];  //对应的课程ID
                $res =  (new ContractModel())->get(['contract_number' => $contract_number]);  //订单表
                $id_ = $res['id']; //订单ID

                $price_ = 0;  //单价
                $course_elimination_arr = []; //课消
                $course_elimination_arr_give = []; //赠送课消
                $pos = -1;
                $payment_balance = 0; //剩余余额
                if($infos[$item['id'].'']['report_status'] == 1){  //课程
                    $res_course = (new CourseContractModel())->get(['student_id' =>$res['student_id'], 'course_id' => $public_course_id,'contract_id' =>$res['id'],'campus_id' => $res['campus_id']]);
                    $payment_balance = $res_course['payment_balance'];
                    $course_ = $res['course'];  //课程
                    $course_elimination_ = $res['course_elimination']; //课消
                    $course_elimination_give_ = $res['give_course_nums']; //赠送课消
                    $course_arr = explode(',',$course_);
                    $course_elimination_arr = explode(',',$course_elimination_);
                    $course_elimination_arr_give = explode(',',$course_elimination_give_);
                    for ($j = 0; $j < count($course_arr); $j ++){
                        if($course_arr[$j] == $course_id){
                            $pos = $j;
                            break;
                        }
                    }
                    //算单价
                    $price_ = round(((($res_course['net_receipts'] - $res_course['assessed_amount']))/($res_course['class_num'])),2); //折后应收 - 分摊金额

                }else if($infos[$item['id'].'']['report_status'] == 2){ //班级
                    $res_grades =  (new GradesContractModel())->get(['student_id' =>$res['student_id'], 'course_id' => $public_course_id,'contract_id' =>$res['id'],'campus_id' => $res['campus_id']]);
                    $payment_balance = $res_grades['payment_balance'];
                    $course_grades_ = $res['grades_course'];  //课程
                    $course_grades_elimination_ = $res['grades_course_elimination']; //课消
                    $course_grades_elimination_give_ = $res['give_grades_course_nums']; //赠送课消
                    $course_grades_arr = explode(',',$course_grades_);
                    $course_elimination_arr = explode(',',$course_grades_elimination_);
                    $course_elimination_arr_give = explode(',',$course_grades_elimination_give_);
                    for ($j = 0; $j < count($course_grades_arr); $j ++){
                        if($course_grades_arr[$j] == $course_id){
                            $pos = $j;
                            break;
                        }
                    }
                    //算单价
                    $price_ = round(((($res_grades['net_receipts'] - $res_grades['assessed_amount']))/($res_grades['class_num'])),2); //折后应收 - 分摊金额

                }else if($infos[$item['id'].'']['report_status'] == 3){ //试听

                }

                if($item['charging'] == 1) {  //如果计费
                    $cell['amount_deducted'] = $price_ * $item['eliminated_nums'];  //扣除金额
                    $cell['eliminated_nums'] = $item['eliminated_nums'];
                }else{
                    $cell['amount_deducted'] = 0;
                    $cell['eliminated_nums'] = 0;
                }


                if($pos >= 0 && $course_elimination_arr_give[$pos] > 0 && $course_elimination_arr[$pos] <= 0){
                    $cell['surplus_class_elimination_give'] = $infos[$item['id'].'']['surplus_class_elimination_give'] - $cell['eliminated_nums']; //赠送剩余课消
                    $cell['surplus_class_elimination'] = $infos[$item['id'].'']['surplus_class_elimination'];
                    $cell['give_status'] = 2;  //赠送课程
                    $cell['amount_deducted'] = 0;  //赠送不计课消金额
                }else{  //先扣非赠送
                    $cell['surplus_class_elimination'] = $infos[$item['id'].'']['surplus_class_elimination'] - $cell['eliminated_nums']; //剩余课消取值实际购买课消数
                    $cell['surplus_class_elimination_give'] = $infos[$item['id'].'']['surplus_class_elimination_give'];
                    $cell['give_status'] = 1;  //非赠送课程
                }



                $cell['status'] = 1; //1表示已上课
                //操作人
                $cell['operatorer'] = xcxapi_get_current_name();  //操作人
                $cell['operatorer_id'] = xcxapi_get_current_user_id();  //操作人ID


                //更新订单表数据
                $contract_cell = [];
                $course_elimination_arr[$pos] = $cell['surplus_class_elimination'];//剩余课消
                $course_elimination_arr_give[$pos] = $cell['surplus_class_elimination_give'];//赠送剩余课消

                $course_elimination_str = implode(',',$course_elimination_arr); //更新后的课消
                $course_elimination_give_str = implode(',',$course_elimination_arr_give); //赠送更新后的课消

                $course_balance = 0;
                $expenditure = 0;
                if($cell['give_status'] = 1) {
                    $expenditure = $res['expenditure']; //支出
                    $expenditure = ($expenditure + $cell['amount_deducted']); //更新支出金额
                    //更新单项缴费余额
                    if($infos[$item['id'].'']['report_status'] == 1) {  //课程
                        $payment_balance = $payment_balance - $cell['amount_deducted'];
                        (new CourseContractModel())->where(['student_id' =>$res['student_id'], 'course_id' => $public_course_id,'contract_id' =>$res['id'],'campus_id' => $res['campus_id']])->update(['payment_balance' => $payment_balance]);

                        if($payment_balance < 0){
                            $cell['arrears_amount'] =  $payment_balance;  //欠费金额
                            $cell['arrears_status'] = 1;//欠费
                        }
                    }else if($infos[$item['id'].'']['report_status'] == 2) {  //班级
                        $payment_balance = $payment_balance - $cell['amount_deducted'];
                        (new GradesContractModel())->where(['student_id' =>$res['student_id'], 'course_id' => $public_course_id,'contract_id' =>$res['id'],'campus_id' => $res['campus_id']])->update(['payment_balance' => $payment_balance]);

                        if($payment_balance < 0){
                            $cell['arrears_amount'] =  $payment_balance;  //欠费金额
                            $cell['arrears_status'] = 1;//欠费
                        }
                    }else if($infos[$item['id'].'']['report_status'] == 3){  //试听

                    }
                    $update_save_data[] = $cell;  //详细课节信息


                    //学费余额
                    $payment_grades_balance = (new GradesContractModel())->where(['contract_id' => $res['id']])->sum('payment_balance');
                    $payment_course_balance = (new CourseContractModel())->where(['contract_id' => $res['id']])->sum('payment_balance');
                    $payment_money_balance = ($payment_course_balance + $payment_grades_balance); //班级与课程余额之和
                    $course_balance = $payment_money_balance; //更新后的账户余额
                }else if($cell['give_status'] = 2){
                    $expenditure = $res['expenditure'];
                    $course_balance = $res['balance'];
                }
                if($infos[$item['id'].'']['report_status'] == 1) {  //课程
                    $contract_cell['course_elimination'] = $course_elimination_str;  //課消剩余
                    $contract_cell['give_course_nums'] = $course_elimination_give_str;  //赠送课消剩余
                }else if($infos[$item['id'].'']['report_status'] == 2){  //班级
                    $contract_cell['grades_course_elimination'] = $course_elimination_str;  //課消剩余
                    $contract_cell['give_grades_course_nums'] = $course_elimination_give_str;  //赠送课消剩余
                }else if($infos[$item['id'].'']['report_status'] == 3){  //试听

                }
                $contract_cell['balance'] = $course_balance; //学费剩余金额
                $contract_cell['expenditure'] = $expenditure; //支出
                $contract_cell['id'] = $id_; //订单ID
                $update_save_contract_data[] = $contract_cell;


                //更新剩余课节详细表
                (new StudentSubjectInfosClassModel())->where(['student_id' => $item['student_id'],'class_subject_id' => $class_subject_id])->update(['surplus_class_elimination' => $cell['surplus_class_elimination']]);
                //更新赠送剩余课节详细表
                (new StudentSubjectInfosClassModel())->where(['student_id' => $item['student_id'],'class_subject_id' => $class_subject_id])->update(['surplus_class_elimination_give' => $cell['surplus_class_elimination_give']]);


                //更新学员表欠费状态
                if($contract_number != null && $contract_number != '---'){
                    $item_arrears = [];
                    $item_arrears['id'] = $item['student_id'];
                    if($course_balance >= 0){
                        $item_arrears['arrears_status'] = 1;  //1表示未欠费
                    }else if($course_balance < 0){
                        $item_arrears['arrears_status'] = 0;  //0表示欠费
                    }

                    $update_arrears_status_student_arr[] = $item_arrears;
                }

            }
			
            if(count($update_arrears_status_student_arr) >0){
                if(!(new StudentModel())->saveAll($update_arrears_status_student_arr)){
                    $this->error('更新欠费信息失败', null, -1, 1);
                }
            }


            if(count($update_save_contract_data) >0){
                if(!(new ContractModel())->saveAll($update_save_contract_data)){
                    $this->error('同步订单信息失败', null, -1, 1);
                }
            }

            if(count($update_save_data) > 0){
                if(!(new StudentSubjectInfosClassModel())->saveAll($update_save_data)){
                    $this->error('上课点名失败', null, -1, 1);
                }
            }



            if(!(new GradesDetailsListsModel())->save(['status' => 1],['id' => $class_id])){
                $this->error('更新上课状态失败', null, -1, 1);
            }
				
			}else if($api_type == 1){
				
	
            $id = $class_id; //节课id
            $result = (new StudentSubjectInfosClassModel())->where(['class_manage_details_id' => $id])->select();
            $class_subject_id = -1;
            $infos = [];
            $public_course_id = -1;  //公共课程ID
            foreach ($result as $key => $value){

                $class_subject_id = $value['class_subject_id'];  //班级ID
                /**************撤销单个课节******************/
                $contract_result_now = (new ContractModel())->get(['contract_number' => $value['contract_number']]); //获取对应订单编号的数据
                $old_eliminated_nums = $value['eliminated_nums'];  //课消数量
                $old_surplus_class_elimination = $value['surplus_class_elimination']; //剩余课时
                $old_surplus_class_elimination_give = $value['surplus_class_elimination_give']; //赠送剩余课时

                $pos_now = -1;
                if($value['report_status'] == 1){  //课程
                    $course_arr_now = explode(',',$contract_result_now['course']);
                    for ($j = 0; $j < count($course_arr_now); $j ++){
                        if($course_arr_now[$j] == $value['course_id']){
                            $pos_now = $j;
                            break;
                        }
                    }
                }else if($value['report_status'] == 2){  //班级
                    $course_arr_now_grades = explode(',',$contract_result_now['grades_course']);
                    for ($j = 0; $j < count($course_arr_now_grades); $j ++){
                        if($course_arr_now_grades[$j] == $value['course_id']){
                            $pos_now = $j;
                            break;
                        }
                    }
                }else if($value['report_status'] == 3){  //试听

                }


                //更新订单表数据
                $contract_cell_update = [];
                if($value['report_status'] == 1){  //课程
                    if($value['give_status'] == 1){
                        $course_elimination_now = $contract_result_now['course_elimination']; //课消
                        $course_elimination_now_arr = explode(',',$course_elimination_now);
                        $course_elimination_now_arr[$pos_now] = ($old_surplus_class_elimination + $old_eliminated_nums);//剩余课消
                        $course_elimination_str_now = implode(',',$course_elimination_now_arr);//更新后的课消
                        $contract_cell_update['course_elimination'] = $course_elimination_str_now;  //课消

                        $res_course = (new CourseContractModel())->get(['student_id' =>$value['student_id'], 'course_id' => $value['course_id'],'contract_id' =>$contract_result_now['id'],'campus_id' => $value['campus_id']]);
                        $res_course['payment_balance'] = $res_course['payment_balance']  + $value['amount_deducted'];
                        (new CourseContractModel())->where(['id' => $res_course['id']])->update(['payment_balance' =>  $res_course['payment_balance']]);


                    }else if($value['give_status'] == 2){
                        $course_elimination_now = $contract_result_now['give_course_nums']; //赠送课消
                        $course_elimination_now_arr = explode(',',$course_elimination_now);
                        $course_elimination_now_arr[$pos_now] = ($old_surplus_class_elimination_give + $old_eliminated_nums);//赠送剩余课消
                        $course_elimination_str_now = implode(',',$course_elimination_now_arr);//更新后的课消
                        $contract_cell_update['give_course_nums'] = $course_elimination_str_now;  //课消
                    }
                }else if($value['report_status'] == 2){  //班级
                    if($value['give_status'] == 1){
                        $course_elimination_now = $contract_result_now['grades_course_elimination']; //课消
                        $course_elimination_now_arr = explode(',',$course_elimination_now);
                        $course_elimination_now_arr[$pos_now] = ($old_surplus_class_elimination + $old_eliminated_nums);//剩余课消
                        $course_elimination_str_now = implode(',',$course_elimination_now_arr);//更新后的课消
                        $contract_cell_update['grades_course_elimination'] = $course_elimination_str_now;  //课消

                        $res_grades = (new GradesContractModel())->get(['student_id' =>$value['student_id'], 'course_id' => $value['course_id'],'contract_id' =>$contract_result_now['id'],'campus_id' => $value['campus_id']]);
                        $res_grades['payment_balance'] = $res_grades['payment_balance']  + $value['amount_deducted'];
                        (new GradesContractModel())->where(['id' => $res_grades['id']])->update(['payment_balance' =>  $res_grades['payment_balance']]);


                    }else if($value['give_status'] == 2){
                        $course_elimination_now = $contract_result_now['give_grades_course_nums']; //赠送课消
                        $course_elimination_now_arr = explode(',',$course_elimination_now);
                        $course_elimination_now_arr[$pos_now] = ($old_surplus_class_elimination_give + $old_eliminated_nums);//赠送剩余课消
                        $course_elimination_str_now = implode(',',$course_elimination_now_arr);//更新后的课消
                        $contract_cell_update['give_grades_course_nums'] = $course_elimination_str_now;  //课消
                    }

                }else if($value['report_status'] == 3){  //试听

                }

                $expenditure = $contract_result_now['expenditure']; //支出
                $expenditure  =  ($expenditure - $value['amount_deducted']); //更新支出金额

                //学费余额
                $payment_grades_balance = (new GradesContractModel())->where(['contract_id' => $contract_result_now['id']])->sum('payment_balance');
                $payment_course_balance = (new CourseContractModel())->where(['contract_id' => $contract_result_now['id']])->sum('payment_balance');
                $payment_money_balance = ($payment_course_balance + $payment_grades_balance); //班级与课程余额之和


                $course_balance = $payment_money_balance; //更新后的账户学费余额

                $balance_now = $course_balance; //更新余额
                $contract_id = $contract_result_now['id']; //订单ID

                $contract_cell_update['balance'] = $balance_now;  //余额
                $contract_cell_update['expenditure'] = $expenditure; //支出金额

                if(count($contract_cell_update) > 0){
                    (new ContractModel())->where(['id' => $contract_id])->update($contract_cell_update);
                }
                /*****************END************************/
                $item = [];
                $item['contract_number'] = $value['contract_number'];
                $item['id'] = $value['id'];
                $item['course_id'] = $value['course_id'];
                if($value['give_status'] == 1) {
                    $item['surplus_class_elimination'] = ($old_surplus_class_elimination + $old_eliminated_nums);
                    $item['surplus_class_elimination_give'] = $value['surplus_class_elimination_give'];
                }
                if($value['give_status'] == 2) {
                    $item['surplus_class_elimination_give'] = ($old_surplus_class_elimination_give + $old_eliminated_nums);
                    $item['surplus_class_elimination'] = $value['surplus_class_elimination'];
                }
                $item['charging'] =  $value['charging'];
                $item['report_status'] =  $value['report_status'];
                $public_course_id = $value['course_id'];
                $postion_key = $item['id'].'';
                $infos[$postion_key] = $item;
            }


            $update_save_data = [];
            $update_save_contract_data = [];
            $update_arrears_status_student_arr = [];  //欠费数组
            $arr_json_lists = $data;
            for ($i = 0; $i < count($arr_json_lists); $i++) {
                $item = $arr_json_lists[$i];
                $cell = [];
                $cell['attendance'] = $item['attendance'];  //出勤
                $cell['charging'] = $item['charging'];  //计费

                $cell['id'] = $item['id'];  //id
                $cell['student_id'] = $item['student_id'];  //student_id
                $cell['attendance_reasons'] = $item['attendance_reasons'];  //缺勤reasons
                $cell['remarks'] = $item['remarks'];  //备注
                $cell['remarks_area'] = $item['remarks_area'];  //课节备注
                $cell['content_area'] = $item['content_area'];  //课节内容

                $contract_number = $infos[$item['id'].'']['contract_number'];  //对应的订单号
                $course_id = $infos[$item['id'].'']['course_id'];  //对应的课程ID
                $res =  (new ContractModel())->get(['contract_number' => $contract_number]);  //订单表
                $id_ = $res['id']; //订单ID

                $price_ = 0;  //单价
                $course_elimination_arr = []; //课消
                $course_elimination_arr_give = []; //赠送课消
                $pos = -1;
                $payment_balance = 0; //剩余余额
                if($infos[$item['id'].'']['report_status'] == 1){  //课程
                    $res_course = (new CourseContractModel())->get(['student_id' =>$res['student_id'], 'course_id' => $public_course_id,'contract_id' =>$res['id'],'campus_id' => $res['campus_id']]);
                    $payment_balance = $res_course['payment_balance'];
                    $course_ = $res['course'];  //课程
                    $course_elimination_ = $res['course_elimination']; //课消
                    $course_elimination_give_ = $res['give_course_nums']; //赠送课消
                    $course_arr = explode(',',$course_);
                    $course_elimination_arr = explode(',',$course_elimination_);
                    $course_elimination_arr_give = explode(',',$course_elimination_give_);
                    for ($j = 0; $j < count($course_arr); $j ++){
                        if($course_arr[$j] == $course_id){
                            $pos = $j;
                            break;
                        }
                    }
                    //算单价
                    $price_ = round(((($res_course['net_receipts'] - $res_course['assessed_amount']))/($res_course['class_num'])),2); //折后应收 - 分摊金额

                }else if($infos[$item['id'].'']['report_status'] == 2){ //班级
                    $res_grades = (new GradesContractModel())->get(['student_id' =>$res['student_id'], 'course_id' => $public_course_id,'contract_id' =>$res['id'],'campus_id' => $res['campus_id']]);
                    $payment_balance = $res_grades['payment_balance'];
                    $course_grades_ = $res['grades_course'];  //课程
                    $course_grades_elimination_ = $res['grades_course_elimination']; //课消
                    $course_grades_elimination_give_ = $res['give_grades_course_nums']; //赠送课消
                    $course_grades_arr = explode(',',$course_grades_);
                    $course_elimination_arr = explode(',',$course_grades_elimination_);
                    $course_elimination_arr_give = explode(',',$course_grades_elimination_give_);
                    for ($j = 0; $j < count($course_grades_arr); $j ++){
                        if($course_grades_arr[$j] == $course_id){
                            $pos = $j;
                            break;
                        }
                    }
                    //算单价
                    $price_ = round(((($res_grades['net_receipts'] - $res_grades['assessed_amount']))/($res_grades['class_num'])),2); //折后应收 - 分摊金额

                }else if($infos[$item['id'].'']['report_status'] == 3){ //试听

                }



                if($item['charging'] == 1) {  //如果计费
                    $cell['amount_deducted'] = $price_ * $item['eliminated_nums'];  //扣除金额
                    $cell['eliminated_nums'] = $item['eliminated_nums'];
                }else{
                    $cell['amount_deducted'] = 0;
                    $cell['eliminated_nums'] = 0;
                }

                if($pos >= 0 && $course_elimination_arr_give[$pos] > 0 && $course_elimination_arr[$pos] <= 0){  //先扣非赠送
                    $cell['surplus_class_elimination_give'] = $infos[$item['id'].'']['surplus_class_elimination_give'] - $cell['eliminated_nums']; //赠送剩余课消
                    $cell['surplus_class_elimination'] = $infos[$item['id'].'']['surplus_class_elimination'];
                    $cell['give_status'] = 2;  //赠送课程
                    $cell['amount_deducted'] = 0;  //赠送不计课消金额
                }else{
                    $cell['surplus_class_elimination'] = $infos[$item['id'].'']['surplus_class_elimination'] - $cell['eliminated_nums']; //剩余课消
                    $cell['surplus_class_elimination_give'] = $infos[$item['id'].'']['surplus_class_elimination_give'];
                    $cell['give_status'] = 1;  //非赠送课程
                }
                $cell['status'] = 1; //1表示已上课

                //操作人
                $cell['operatorer'] = xcxapi_get_current_name();  //操作人
                $cell['operatorer_id'] = xcxapi_get_current_user_id(); //操作人ID
		

                //更新订单表数据
                $contract_cell = [];
                $course_elimination_arr[$pos] = $cell['surplus_class_elimination'];//剩余课消
                $course_elimination_arr_give[$pos] = $cell['surplus_class_elimination_give'];//赠送剩余课消

                $course_elimination_str = implode(',',$course_elimination_arr); //更新后的课消
                $course_elimination_give_str = implode(',',$course_elimination_arr_give); //赠送更新后的课消

                $course_balance = 0;
                $expenditure = 0;
                if($cell['give_status'] = 1) {
                    $expenditure = $res['expenditure']; //支出
                    $expenditure = ($expenditure + $cell['amount_deducted']); //更新支出金额
                    //更新单项缴费余额
                    if($infos[$item['id'].'']['report_status'] == 1) {  //课程
                        $payment_balance = $payment_balance - $cell['amount_deducted'];
                        (new CourseContractModel())->where(['student_id' =>$res['student_id'], 'course_id' => $public_course_id,'contract_id' =>$res['id'],'campus_id' => $res['campus_id']])->update(['payment_balance' => $payment_balance]);

                        if($payment_balance < 0){
                            $cell['arrears_amount'] =  $payment_balance;  //欠费金额
                            $cell['arrears_status'] = 1;//欠费
                        }else{
                            $cell['arrears_amount'] =  0;  //未欠费金额
                            $cell['arrears_status'] = 0;//未欠费
                        }
                    }else if($infos[$item['id'].'']['report_status'] == 2) {  //班级
                        $payment_balance = $payment_balance - $cell['amount_deducted'];
                        (new GradesContractModel())->where(['student_id' =>$res['student_id'], 'course_id' => $public_course_id,'contract_id' =>$res['id'],'campus_id' => $res['campus_id']])->update(['payment_balance' => $payment_balance]);

                        if($payment_balance < 0){
                            $cell['arrears_amount'] =  $payment_balance;  //欠费金额
                            $cell['arrears_status'] = 1;//欠费
                        }else{
                            $cell['arrears_amount'] =  0;  //未欠费金额
                            $cell['arrears_status'] = 0;//未欠费
                        }
                    }else if($infos[$item['id'].'']['report_status'] == 3){  //试听

                    }
                    $update_save_data[] = $cell;  //详细课节信息


                    //学费余额
                    $payment_grades_balance = (new GradesContractModel())->where(['contract_id' => $res['id']])->sum('payment_balance');
                    $payment_course_balance = (new CourseContractModel())->where(['contract_id' => $res['id']])->sum('payment_balance');
                    $payment_money_balance = ($payment_course_balance + $payment_grades_balance); //班级与课程余额之和
                    $course_balance = $payment_money_balance; //更新后的账户余额


                }else if($cell['give_status'] = 2){
                    $expenditure = $res['expenditure'];
                    $course_balance = $res['balance'];
                }
                if($infos[$item['id'].'']['report_status'] == 1) {  //课程
                    $contract_cell['course_elimination'] = $course_elimination_str;  //課消剩余
                    $contract_cell['give_course_nums'] = $course_elimination_give_str;  //赠送课消剩余
                }else if($infos[$item['id'].'']['report_status'] == 2){  //班级
                    $contract_cell['grades_course_elimination'] = $course_elimination_str;  //課消剩余
                    $contract_cell['give_grades_course_nums'] = $course_elimination_give_str;  //赠送课消剩余
                }else if($infos[$item['id'].'']['report_status'] == 3){  //试听

                }

                $contract_cell['balance'] = $course_balance; //剩余金额
                $contract_cell['expenditure'] = $expenditure; //支出金额
                $contract_cell['id'] = $id_; //订单ID
                $update_save_contract_data[] = $contract_cell;

                //更新课节表剩余课节数量
                (new StudentSubjectInfosClassModel())->where(['student_id' => $item['student_id'],'class_subject_id' => $class_subject_id])->update(['surplus_class_elimination' => $cell['surplus_class_elimination']]);
                //更新课节表赠送剩余课节数量
                (new StudentSubjectInfosClassModel())->where(['student_id' => $item['student_id'],'class_subject_id' => $class_subject_id])->update(['surplus_class_elimination_give' => $cell['surplus_class_elimination_give']]);

                //更新学员表欠费状态
                if($contract_number != null && $contract_number != '---'){
                    $item_arrears = [];
                    $item_arrears['id'] = $item['student_id'];
                    if($course_balance >= 0){
                        $item_arrears['arrears_status'] = 1;  //1表示未欠费
                    }else if($course_balance < 0){
                        $item_arrears['arrears_status'] = 0;  //0表示欠费
                    }

                    $update_arrears_status_student_arr[] = $item_arrears;
                }


            }

            if(count($update_arrears_status_student_arr) >0){
                if(!(new StudentModel())->saveAll($update_arrears_status_student_arr)){
                    $this->error('更新欠费信息失败', null, -1, 1);
                }
            }

            if(count($update_save_contract_data) >0){
                if(!(new ContractModel())->saveAll($update_save_contract_data)){
                    $this->error('同步订单信息失败', null, -1, 1);
                }
            }

            if(count($update_save_data) > 0){
                if(!(new StudentSubjectInfosClassModel())->saveAll($update_save_data)){
                    $this->error('更改信息失败', null, -1, 1);
                }
            }

			}
			
			
			

			

        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

    /**
     * User: wufeng
     * Date: 2020/02/21.
     *
     * @param $params
     *
     * @return mixed
     */
    public function signInLists($params)
    {
        try {
            $page = isset($params['page']) ? (int) $params['page'] : 1;
            $listRows = isset($params['limit']) ? (int) $params['limit'] : 10;
            $where = [];
            if (isset($params['word']) && '' !== $params['word']) {
                $where['class_grades_name|class_room|teacher'] = ['like', $params['word'].'%'];
            }
            $where['graduation_status'] = 0; //未结业
            //课程id
            if (isset($params['course_id']) && '' !== $params['course_id']) {
                $where['course_id'] = $params['course_id'];
            }

            $where['campus_id'] = ['in', xcxapi_get_current_campus_id()];

            //时间段
            if (isset($params['start_date']) && '' !== $params['start_date'] && isset($params['end_date']) && '' !== $params['end_date']) {
                $where['class_date'] = ['between', [$params['start_date'], $params['end_date']]];
            }

            $this->data = (new GradesDetailsListsModel())
				->where($where)
				->order('id desc')
                ->paginate($listRows, false, ['page' => $page])
                ->toArray();
            if (!empty($this->data)) {
                $i = 0;
                foreach ($this->data['data'] as &$item) {
                    $i = $i + 1;
                    $item['course_name'] = (new CourseModel())->get($item['course_id'])['course_name'];
                    $item['campus_name'] = (new CampusModel())->get($item['campus_id'])['campus_name'];
                    $res = (new GradesDetailsModel())->get($item['class_manage_id']);
                    $item['course_class_name'] = $item['course_name'].'第'.$i.'节';

                    $start = strtotime($item['class_subject_start']);  //开始时间
                    $end = strtotime($item['class_subject_end']);  //结束时间
                    $item['course_date_week_time'] = $item['class_date'].'-'.$item['weekday'].'-'.$item['class_subject_start'].'-'.$item['class_subject_end'];
                    $item['class_length'] = ceil(($end - $start) / 60).'分钟';
                    $nums = (new StudentSubjectInfosClassModel())->where(['class_manage_details_id' => $item['id']])->select();
                    if (0 === (int) $item['status']) {  //未上课
                        $item['actual_number'] = '0/'.\count($nums);
                    } elseif (1 === (int) $item['status']) {  //已上课
                        $already_nums = 0;
                        foreach ($nums as $key => $value) {
                            if (1 === (int) $value['attendance']) {
                                ++$already_nums;
                            }
                        }
                        $item['actual_number'] = $already_nums.'/'.\count($nums);
                    }
                    $item['student_nums'] = $res['preoccupation'];
                    $result = (new StudentSubjectClassModel())->where(['class_subject_id' => $item['class_manage_id']])->select();
                    $student_id_arr = [];
                    $nums = 0;
                    foreach ($result as $key => $value) {
                        if (!\in_array($value['student_id'], $student_id_arr, true)) {
                            $nums = $nums + 1;
                            $student_id_arr[] = $value['student_id'];
                        }
                    }

                    if (0 === (int) $item['student_nums']) {
                        $item['student_nums'] = $nums.'/'.'不限';
                    } else {
                        $item['student_nums'] = $nums.'/'.$item['student_nums'];
                    }
                }
            }
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

    /**
     * 编辑客户
     * User: wufeng
     * Date: 2019/5/24.
     *
     * @param $params
     *
     * @return array
     */
    public function editCustomer($params)
    {
        try {
            if (0 === (int) $params['user_id']) {
                $params['course_consultant_type'] = 2; //公海
                $params['course_consultant'] = '公海';
                $params['user_id'] = 0;
            } else {
                $params['course_consultant_type'] = 1; //自己
                $params['user_id'] = $params['user_id'];
                $params['course_consultant'] = (new UserModel())->get($params['user_id'])['name'];
            }
            unset($params['nonceStr'],$params['sign'],$params['version']);
            $params['birth'] = $params['birth'] ? $params['birth'] : null;
            $params['school_class'] = $params['school_class'] ? $params['school_class'] : '--';
            //家长信息修改 开始
            $check = (new ParentInformationModel())->where(['student_id' => $params['id']])->find();
            if ($check['username'] !== $params['guardian_phone']) {
                (new ParentInformationModel())->where(['student_id' => $params['id']])->update(['username' => $params['guardian_phone'], 'name' => $params['guardian']]);
            }
            //家长信息修改 结束
            (new StudentModel())->isUpdate(true)->save($params);
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }
	
	  /**
     * 删除课节
     * User: chenben
     * Date: 2020/3/26.
     *
     * @param $params
     *
     * @return array
     */
    public function deleteClass($params)
    {
        try {
            $result = (new GradesDetailsListsModel())->get(['id' => $params['id']]);
            $result_class_status = (new GradesDetailsModel())->get(['id' => $result['class_manage_id']])['class_status'];

            if($result_class_status == 0){
                if (!(new GradesDetailsListsModel())->where(['id' => input('id')])->delete()) {
                    $this->error('删除课节失败', null, '', 1);
                }

                if((new StudentSubjectInfosClassModel())->where(['class_manage_details_id' => input('id')])->count() > 0){
                    if (!(new StudentSubjectInfosClassModel())->where(['class_manage_details_id' => input('id')])->delete()) {
                        $this->error('删除详情课节失败', null, '', 1);
                    }
                }

            }else{
               //补课班级
                $student_lesson_result = (new StudentSubjectInfosClassModel())->where(['class_manage_details_id' => input('id')])->select();

                foreach ($student_lesson_result as $key => $value){
                    $lessons_id = $value['lessons_id']; //所绑课程ID
                    if(!(new StudentSubjectInfosClassModel())->where(['id' => $lessons_id])->update(['lessons_status' => 0])){
                        $this->error('更新该补课学生状态失败', null, -1, 1);
                    }
                }

                if(!(new StudentSubjectClassModel())->where(['class_subject_id' => $result['class_manage_id']])->delete()){
                    $this->error('删除分班补课学生失败', null, -1, 1);
                }

                if(!(new GradesDetailsListsModel())->where(['id' => input('id')])->delete()){
                    $this->error('删除该补课学生课节失败', null, -1, 1);
                }
                if(!(new GradesDetailsModel())->where(['id' => $result['class_manage_id']])->delete()){
                    $this->error('删除该补课学生班级失败', null, -1, 1);
                }

                if(!(new StudentSubjectInfosClassModel())->where(['class_manage_details_id' => input('id')])->delete()){

                    $this->error('删除补课所有学生课节失败', null, -1, 1);
                }

            }

		  
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }
	
	  /**
     * 撤销课节
     * User: chenben
     * Date: 2020/3/26.
     *
     * @param $params
     *
     * @return array
     */
    public function cancleClass($params)
    {
        try {
			$id = $params['id']; //节课ID
            $result = (new StudentSubjectInfosClassModel())->where(['class_manage_details_id' => $id])->select();
            $result_list_id = (new GradesDetailsListsModel())->get(['id' => $id])['class_manage_id']; //班级ID
            $class_subject_id = $result_list_id;

            $infos = [];
            $contract_update = [];
            $update_arrears_status_student_arr = [];
            foreach ($result as $key => $value){
                if($value['lessons_status'] == 1) {  //存在补课记录
                    $res = (new StudentSubjectInfosClassModel())->get(['lessons_id' => $value['id']]);
                    $res_gradeslist = (new GradesDetailsListsModel())->get(['id' => $res['class_manage_details_id']]);
                    if ($res_gradeslist['status'] == 1) {  //已上课
                        $this->success('已安排补课，需先撤销补课记录，才能撤销本次课节', '', '', 1);
                    }

                }
                //edu_class_subject_student_infos表
                $item = [];
                $item['id'] = $value['id'];   //详情ID
                $item['attendance_reasons'] = null;   //缺勤原因
                $item['remarks'] = null;//备注
                $item['remarks_area'] = null; //课节备注
                $item['content_area'] = null; //课节内容
                $item['attendance'] = 0; //考勤
                $item['charging'] = 0;  //计费
                $item['eliminated_nums'] = 0; //课消节数
                if($value['give_status'] == 1){  //非赠送
                    $item['surplus_class_elimination'] = $value['surplus_class_elimination'] + $value['eliminated_nums']; // 该课程剩余课时，默认为-1
                    $item['surplus_class_elimination_give'] = $value['surplus_class_elimination_give'];
                }else  if($value['give_status'] == 2){  //赠送
                    $item['surplus_class_elimination_give'] = $value['surplus_class_elimination_give'] + $value['eliminated_nums']; // 该课程赠送剩余课时，默认为-1
                    $item['surplus_class_elimination'] =  $value['surplus_class_elimination'];
                }
                $item['amount_deducted'] = 0; // 扣除金额
                $item['arrears_status'] = 0; // 欠费标志
                $item['arrears_amount'] = 0; // 欠费金额
                $item['status'] = 0; //表示未上课
                $item['lessons_status'] = 0;
                $item['operatorer'] = xcxapi_get_current_name();  //操作人
                $item['operatorer_id'] = xcxapi_get_current_user_id(); //操作人ID

                //edu_contract订单表
                $contract_number = $value['contract_number']; //对应订单编号
                $contract_result = (new ContractModel())->get(['contract_number' => $contract_number]); //获取对应订单编号的数据
                $contract_item = [];
                $contract_item['contract_number'] = $contract_number;//订单编号

                if($value['give_status'] == 1) {  //非赠送
                    $expenditure = $contract_result['expenditure']; //支出
                    $expenditure = ($expenditure - $value['amount_deducted']); //更新支出金额

                    if($value['report_status'] == 1) {  //课程
                        $res_course = (new CourseContractModel())->get(['student_id' =>$value['student_id'], 'course_id' => $value['course_id'],'contract_id' =>$contract_result['id'],'campus_id' => $value['campus_id']]);
                        $res_course['payment_balance'] =  $res_course['payment_balance'] + $value['amount_deducted'];
                        (new CourseContractModel())->where(['id' => $res_course['id']])->update(['payment_balance' =>  $res_course['payment_balance']]);


                    }else if($value['report_status'] == 2){ //班级
                        $res_grades = (new GradesContractModel())->get(['student_id' =>$value['student_id'], 'course_id' => $value['course_id'],'contract_id' =>$contract_result['id'],'campus_id' => $value['campus_id']]);
                        $res_grades['payment_balance'] =  $res_grades['payment_balance'] + $value['amount_deducted'];
                        (new GradesContractModel())->where(['id' => $res_grades['id']])->update(['payment_balance' =>  $res_grades['payment_balance']]);

                    }else if($value['report_status'] == 3){ //试听

                    }
                    //学费余额
                    $payment_grades_balance = (new GradesContractModel())->where(['contract_id' => $contract_result['id']])->sum('payment_balance');
                    $payment_course_balance = (new CourseContractModel())->where(['contract_id' => $contract_result['id']])->sum('payment_balance');
                    $payment_money_balance = ($payment_course_balance + $payment_grades_balance); //班级与课程余额之和

                    $contract_item['balance'] = $payment_money_balance; //订单余额更新
                    $contract_item['expenditure'] = $expenditure; //支出金额
                }

                $pos = -1;
                if($value['report_status'] == 1){  //课程
                    $course_arr = explode(',',$contract_result['course']);
                    for ($j = 0; $j < count($course_arr); $j ++){
                        if($course_arr[$j] == $value['course_id']){
                            $pos = $j;
                            break;
                        }
                    }
                    if($value['give_status'] == 1){  //非赠送
                        $course_elimination_arr = explode(',',$contract_result['course_elimination']);
                        $course_elimination_arr[$pos] = $item['surplus_class_elimination'];//剩余课消
                        $contract_item['course_elimination'] = implode(',',$course_elimination_arr);
                    }else if($value['give_status'] == 2){  //赠送
                        $course_elimination_arr_give = explode(',',$contract_result['give_course_nums']);
                        $course_elimination_arr_give[$pos] = $item['surplus_class_elimination_give'];//赠送剩余课消
                        $contract_item['give_course_nums'] =  implode(',',$course_elimination_arr_give);
                    }

                }else if($value['report_status'] == 2){  //班级
                    $grades_course_arr = explode(',',$contract_result['grades_course']);
                    for ($j = 0; $j < count($grades_course_arr); $j ++){
                        if($grades_course_arr[$j] == $value['course_id']){
                            $pos = $j;
                            break;
                        }
                    }
                    if($value['give_status'] == 1){  //非赠送
                        $course_elimination_arr = explode(',',$contract_result['grades_course_elimination']);
                        $course_elimination_arr[$pos] = $item['surplus_class_elimination'];//剩余课消
                        $contract_item['grades_course_elimination'] = implode(',',$course_elimination_arr);
                    }else if($value['give_status'] == 2){  //赠送
                        $course_elimination_arr_give = explode(',',$contract_result['give_grades_course_nums']);
                        $course_elimination_arr_give[$pos] = $item['surplus_class_elimination_give'];//赠送剩余课消
                        $contract_item['give_grades_course_nums'] = implode(',',$course_elimination_arr_give);
                    }

                }else if($value['report_status'] == 3){ //试听

                }
                $contract_item['id'] = $contract_result['id'];
                $contract_update[] = $contract_item;
                $infos[] = $item;

                //更新课节表剩余课节数量
                (new StudentSubjectInfosClassModel())->where(['student_id' => $value['student_id'],'class_subject_id' => $class_subject_id])->update(['surplus_class_elimination' => $item['surplus_class_elimination']]);
                //更新课节表剩余课节数量
                (new StudentSubjectInfosClassModel())->where(['student_id' => $value['student_id'],'class_subject_id' => $class_subject_id])->update(['surplus_class_elimination_give' => $item['surplus_class_elimination_give']]);


                //更新学员表欠费状态
                if($contract_number != null && $contract_number != '---'){
                    $item_arrears = [];
                    $item_arrears['id'] = $value['student_id'];
                    if($contract_item['balance'] >= 0){
                        $item_arrears['arrears_status'] = 1;  //1表示未欠费
                    }else if($contract_item['balance'] < 0){
                        $item_arrears['arrears_status'] = 0;  //0表示欠费
                    }
                    $update_arrears_status_student_arr[] = $item_arrears;
                }


             }

            if(count($update_arrears_status_student_arr) >0){
                if(!(new StudentModel())->saveAll($update_arrears_status_student_arr)){
                    $this->error('更新学生欠费状态失败', null, -1, 1);
                }
            }


             /*******删除未开课的补课记录********/
            foreach ($result as $key => $value) {
                if ($value['lessons_status'] == 1) {  //存在补课记录
                    $res = (new StudentSubjectInfosClassModel())->get(['lessons_id' => $value['id']]);
                        if($res){
                            $res_gradeslist = (new GradesDetailsListsModel())->get(['id' => $res['class_manage_details_id']]);
                            if($res_gradeslist){
                                if ($res_gradeslist['status'] == 0) {  //未上课

                                    if($res['follow_status'] == 1){  //新开班课节

                                        (new GradesDetailsListsModel())->where(['id' => $res['class_manage_details_id']])->delete();//删除节课列表
                                        (new GradesDetailsModel())->where(['id' => $res['class_subject_id']])->delete();
                                        (new StudentSubjectClassModel())->where(['class_subject_id' => $res['class_subject_id']])->delete();
                                        (new StudentSubjectInfosClassModel())->where(['class_subject_id' => $res['class_subject_id']])->delete();


                                    }else if($res['follow_status'] == 2){  //跟班课节


                                        (new StudentSubjectClassModel())->where(['class_subject_id' => $res['class_subject_id'], 'student_type' => 3, 'student_id' => $res['student_id']])->delete();
                                        (new StudentSubjectInfosClassModel())->where(['class_subject_id' => $res['class_subject_id'],'follow_status' => 2, 'student_id' => $res['student_id']])->delete();

                                    }

                                }
                            }

                        }

                }
            }
            /***************END*******************/


             //edu_class_subject_student_infos表更新上课状态
            if(count($infos) > 0){
                if(!(new StudentSubjectInfosClassModel())->saveAll($infos)){
                    $this->error('更新当前课节失败', null, -1, 1);
                }
            }

            //edu_contract表更新上课状态
            if(count($contract_update) > 0){
                if(!(new ContractModel())->saveAll($contract_update)){
                    $this->error('更新订单信息失败', null, -1, 1);
                }

            }

            //edu_class_manage_details_lists表更新上课状态
            if(!(new GradesDetailsListsModel())->save(['status' => 0],['id' => $id])){
                $this->error('请勿重复更新状态', null, -1, 1);
            }
		  
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

	/**
	 * 跟进状态列表
	 * User: wufeng
	 * Date: 2020/04/18
	 *
	 * @param $params
	 * @return array
	 */
	public function followUp($params)
	{
		try {
			//跟进状态
			$this->data['follow_up'] = (new DictionaryModel())
				->where('type', 6)
				->field('id,name')
				->select()
				->toArray()
			;

		} catch (\Exception $e) {
			$this->errorMessage($e, $params);
		}

		return $this->return;
	}
}
